using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using Android.App;
using Android.Content;
using Android.GoogleMaps;
using Android.Graphics;
using Android.OS;
using Android.Preferences;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using NorthStar.Passenger.Application;
using TheNorthStar.Api.Results;

namespace NorthStar.Passenger
{
    [Activity(Label = "Where is my taxi?")]
    public class TaxiMapActivity : MapActivity
    {
        Booking booking = null;
        private ISharedPreferences _preferences;
        private MapView map;
        private System.Timers.Timer timer;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            

            timer = new System.Timers.Timer(15000);

            timer.Elapsed += (sender, e) =>
            {
                ThreadPool.QueueUserWorkItem(x => UpdateMap());
            };

            _preferences = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
            string bookingJson = _preferences.GetString("lastBookingRef", string.Empty);
            if (bookingJson != string.Empty)
            {
                booking = Newtonsoft.Json.JsonConvert.DeserializeObject<Booking>(bookingJson);

                if (booking.Status == "CONFIRMED")
                {
                    SetContentView(Resource.Layout.Map);

                    map = InitMap();

                    var customOverlay = new CustomMapOverlay(new GeoPoint((int)((float)booking.Latitude * 1E6), (int)((float)booking.Longitude * 1E6)));
                    map.Overlays.Add(customOverlay);
                    map.Controller.AnimateTo(new GeoPoint((int)((float)booking.Latitude * 1E6), (int)((float)booking.Longitude * 1E6)));

                   timer.Start();
                }
                else
                {
                    CreateAlert();
                }
            }
            else
            {
                CreateAlert();

            }

            // Create your application here
        }
        protected override void OnDestroy()
        {
            base.OnDestroy();
            timer.Stop();
        }
        private void UpdateMap()
        {


            ApiService api = new ApiService(Helper.GetServer(ApplicationContext));
            var result = api.GetBooking(booking.BookingId);
            booking = Newtonsoft.Json.JsonConvert.DeserializeObject<Booking>(result);
            
            RunOnUiThread(()=>
                              {
                                  map.Overlays.Clear();
                                  var customOverlay = new CustomMapOverlay(new GeoPoint((int)((float)booking.Latitude * 1E6), (int)((float)booking.Longitude * 1E6)));
                                  map.Overlays.Add(customOverlay);
                                  map.Controller.AnimateTo(new GeoPoint((int)((float)booking.Latitude * 1E6), (int)((float)booking.Longitude * 1E6)));
                              });
            
        }

      

        private void CreateAlert()
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.SetTitle("No Booking")
                .SetMessage("You must have a active booking. Would you like to create one now?")
                .SetPositiveButton("Yes",
                    (sender, e) =>
                    {
                        this.StartActivity(typeof(BasicBookTaxiActivity));
                        this.Finish();
                    })
                    .SetNegativeButton("No", (sender, e) => this.Finish());

            AlertDialog alert = builder.Create();
            alert.Show();
        }

        MapView InitMap()
        {
            var map = FindViewById<MapView>(Resource.Id.map);

            map.Clickable = true;
            map.Traffic = false;
            map.Satellite = false;
           
            map.Controller.SetZoom(19);

            return map;
        }

        protected override bool IsRouteDisplayed
        {
            get { return false; }
        }
    }

    class CustomMapOverlay : Overlay
    {
        private readonly GeoPoint _latlng;

        public CustomMapOverlay(GeoPoint latlng)
        {
            _latlng = latlng;
        }

        public override void Draw(Android.Graphics.Canvas canvas, MapView mapView, bool shadow)
        {
            base.Draw(canvas, mapView, shadow);

            var paint = new Paint();
            paint.AntiAlias = true;
            paint.Color = Color.Purple;

            // to draw fixed graphics that will not move or scale with the map
            //canvas.DrawRect (0, 0, 100, 100, paint);

            // to draw graphics at a geocoded location that move and scale with the map
           // var gp = new GeoPoint((int)(-35.28351 * 1E6), (int)(149.126125 * 1E6));
            var pt = mapView.Projection.ToPixels(_latlng, null);
            float distance = mapView.Projection.MetersToEquatorPixels(10);

            canvas.DrawRect(pt.X, pt.Y, pt.X + distance, pt.Y + distance, paint);
        }
    }
}